package com.itheima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.admin.feign.AdChannelFeign;
import com.itheima.admin.pojo.AdChannel;
import com.itheima.article.dto.ArticleInfoDto;
import com.itheima.article.feign.ApArticleFeign;
import com.itheima.article.feign.AuthorFeign;
import com.itheima.article.pojo.ApArticle;
import com.itheima.article.pojo.ApArticleConfig;
import com.itheima.article.pojo.ApArticleContent;
import com.itheima.article.pojo.ApAuthor;
import com.itheima.common.pojo.PageInfo;
import com.itheima.common.pojo.PageRequestDto;
import com.itheima.common.pojo.Result;
import com.itheima.common.pojo.VerifyMessage;
import com.itheima.media.dto.ContentNode;
import com.itheima.media.dto.WmNewsDtoSave;
import com.itheima.media.dto.WmNewsVo;
import com.itheima.media.mapper.WmNewsMapper;
import com.itheima.media.mapper.WmUserMapper;
import com.itheima.media.pojo.WmNews;
import com.itheima.media.pojo.WmUser;
import com.itheima.media.service.WmNewsService;
import com.itheima.search.document.ArticleInfoDocument;
import com.itheima.search.feign.SearchFeign;
import org.checkerframework.checker.units.qual.K;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author 作者
 * @since 2021-08-20
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Autowired
    private ApArticleFeign apArticleFeign;

    @Autowired
    private AdChannelFeign adChannelFeign;

    @Autowired
    private AuthorFeign authorFeign;

    @Autowired
    private WmUserMapper wmUserMapper;

    @Autowired
    private SearchFeign searchFeign;


    /**
     * 定时发布文章、同步文章
     * @param wmNews
     */
    @Override
    public void batchModify(List<WmNews> wmNews) {
        //2：修改状态9（发布）
        //3：同步
        for (WmNews wmNew : wmNews) {
            wmNew.setStatus(9);
            //同步
            sync(wmNew);
            //修改状态
            wmNewsMapper.updateById(wmNew);
        }
    }

    /***
     * 根据ID查询文章详情
     * @param id
     * @return
     */
    @Override
    public WmNewsVo findDetailById(Integer id) {
        //查询WmNews
        WmNews wmNews = wmNewsMapper.selectById(id);

        //查询作者
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        WmNewsVo wmNewsVo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        wmNewsVo.setAuthorName(wmUser.getName());
        return wmNewsVo;
    }


    /****
     * 人工审核 审核->2:审核失败   8：定时发布     9：发布
     * @param id
     * @param status
     */
    @Override
    public void verify(Integer id, Integer status) {
        //修改状态
        WmNews wmNews = new WmNews();
        wmNews.setId(id);
        wmNews.setStatus(status);
        wmNewsMapper.updateById(wmNews);

        //直接同步即可
        if(status==9){
            wmNews = wmNewsMapper.selectById(id);
            syncArticle(wmNews);
        }
    }



    /**
     * 分页查询
     * @param dto
     * @return
     */
    @Override
    public PageInfo<WmNewsVo> pageForCondition(PageRequestDto<WmNews> dto) {
        //1:查询总数量   select count(*) from table where xx
        Long total = wmNewsMapper.findWmNewsCount(dto.getBody());

        //2:查询集合数据 select * from table where xxx limit #{start},#{end}
        //                                                    索引、最多查询条数
        //                                                    start = (dto.getPage()-1)*dot.getSize()
        List<WmNewsVo> wmNewsVos = wmNewsMapper.findWmNewsPages(dto);

        //3:封装返回的分页数据
        Long pages = total%dto.getSize()==0? total/dto.getSize() : total/dto.getSize()+1;
        PageInfo<WmNewsVo> pageInfo = new PageInfo<WmNewsVo>(dto.getPage(),dto.getSize(),total,pages,wmNewsVos);
        return pageInfo;
    }


    /***
     * 同步处理
     * @param resultMap
     */
    @Override
    public void autoVerify(Map<String, Object> resultMap) {
        //1:获取ID
        Integer id =Integer.valueOf(resultMap.get("attach").toString());
        //2:获取状态
        Boolean result = (Boolean) resultMap.get("result");

        //1：检测状态，true|false  true：审核通过   false：审核失败
        if(result){
            //2：true：审核通过-修改状态
            WmNews wmNews = wmNewsMapper.selectById(id);
            syncArticle(wmNews);
        }else{
            //3：false：审核失败
            //        直接修改状态
            WmNews wmNews = new WmNews();
            wmNews.setId(id);
            wmNews.setStatus(3);//审核失败【交由人工审核】
            wmNewsMapper.updateById(wmNews);
        }
    }

    /**
     * 文章同步
     */
    private void syncArticle(WmNews wmNews) {
        if(wmNews!=null){
            if(wmNews.getPublishTime()!=null){
                //  2.1 定时发布，定时同步
                wmNews.setStatus(8);
            }else{
                //同步数据
                sync(wmNews);
            }
            //状态修改
            wmNewsMapper.updateById(wmNews);
        }
    }

    /**
     * 同步->远程调用
     * @param wmNews
     */
    private void sync(WmNews wmNews) {
        //  2.2 立即发布，则数据同步
        wmNews.setStatus(9);

        //  2.3 ArticleInfoDto
        ArticleInfoDto dto = new ArticleInfoDto();

        Result<AdChannel> adChannelResult = adChannelFeign.findById(wmNews.getChannelId());
        AdChannel adChannel = adChannelResult.getData();
        Result<ApAuthor> apAuthorResult = authorFeign.getByUserId(wmNews.getUserId());
        ApAuthor apAuthor = apAuthorResult.getData();

        //ApArticle
        ApArticle apArticle = new ApArticle();
        apArticle.setTitle(wmNews.getTitle());
        apArticle.setAuthorId(apAuthor.getId());   //作者ID
        apArticle.setAuthorName(apAuthor.getName()); //作者名字
        apArticle.setChannelId(wmNews.getChannelId());  //频道ID
        apArticle.setChannelName(adChannel.getName()); //频道名字
        apArticle.setLayout(wmNews.getType()); //类型：有图、无图、三图
        apArticle.setFlag(0);   //普通文章
        apArticle.setImages(wmNews.getImages()); //图片
        apArticle.setLabels(wmNews.getLabels()); //标签
        apArticle.setCreatedTime(wmNews.getCreatedTime());

        // ApArticleConfig
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setIsDown(0);
        apArticleConfig.setIsDelete(0);

        //ApArticleContent
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setContent(wmNews.getContent());

        dto.setApArticle(apArticle);
        dto.setApArticleContent(apArticleContent);
        dto.setApArticleConfig(apArticleConfig);
        apArticleFeign.saveArticle(dto);
        //实现数据同步到ElasticSearch中
        ArticleInfoDocument doc = JSON.parseObject(JSON.toJSONString(apArticle),ArticleInfoDocument.class);
        searchFeign.saveToEs(doc);
    }


    /***
     * 上架、下架
     * @param id
     * @param enable
     * @return
     */
    @Override
    public int updateUpDown(Integer id, Integer enable) {
        //1）文章一定要存在
        //2）文章一定是审核通过的，才能上架、下架
        return wmNewsMapper.updateUpDown(id,enable);
    }


    /***
     * 根据ID删除
     * @param id
     * @return
     */
    @Override
    public int deleteById(Serializable id) {
        //1：文章必须是 0,1,2的状态
        //2：文章的enable=0下架了
        //3：DELETE wm_news WHERE id=? AND `status` IN(0,1,2) AND `enable`=0
        return wmNewsMapper.deleteWmNewsById(id);
    }

    /**
     * 根据ID查询
     * @param id
     * @return
     */
    @Override
    public WmNewsDtoSave getOneById(Integer id) {
        //1)根据ID查询WmNews
        WmNews wmNews = wmNewsMapper.selectById(id);
        WmNewsDtoSave dtoSave = new WmNewsDtoSave();
        //2)将WmNews转成WmNewsDtoSave
        BeanUtils.copyProperties(wmNews,dtoSave);
        //3)内容转成List<ContentNode>
        List<ContentNode> contentNodes = JSON.parseArray(wmNews.getContent(), ContentNode.class);
        dtoSave.setContent(contentNodes);
        //4)图片转成List<String>
        String[] images = wmNews.getImages().split(",");
        List<String> imageList = Arrays.asList(images);
        dtoSave.setImages(imageList);
        return dtoSave;
    }



    /**
     * 保存文章
     * @param dtoSave
     */
    @Override
    public void save(WmNewsDtoSave dtoSave) {
        //1)将WmNewsDtoSave转成WmNews对象
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dtoSave,wmNews);
        wmNews.setCreatedTime(LocalDateTime.now());
        //wmNews.setUserId(RequestContext.getNodeValue("id"));
        wmNews.setUserId(100);

        //2)将WmNewsDtoSave的content转成JSON字符串，并赋值给WmNews的content
        wmNews.setContent(JSON.toJSONString(dtoSave.getContent()));

        //3)判断封面类型，如果是自动类型，需要从WmNewsDtoSave的content提取图片，并赋值给将WmNewsDtoSave的List<String>images
        fetchImages(dtoSave);

        //4)将WmNewsDtoSave的List<String>images转成以逗号拼接的字符串，并赋值给WmNews的images
        if(dtoSave.getImages()!=null && dtoSave.getImages().size()>0){
            String images = dtoSave.getImages().toString().substring(1, dtoSave.getImages().toString().length() - 1).replace(" ", "");
            wmNews.setImages(images);
        }
        //5)增加操作
        if(dtoSave.getStatus()==1){
            wmNews.setSubmitedTime(LocalDateTime.now());
        }
        //6)如果ID！=null，执行修改
        if(wmNews.getId()!=null){
            wmNewsMapper.updateById(wmNews);
        }else{
            //7)如果ID==null，执行增加
            wmNewsMapper.insert(wmNews);
        }

        //审核->自动审核->向风控系统发消息
        //封装VerifyMessage
        VerifyMessage verifyMessage = new VerifyMessage(wmNews.getContent(),"wmnews_save_queue",String.valueOf(wmNews.getId()));
        kafkaTemplate.send("checkfortext",JSON.toJSONString(verifyMessage));
    }

    /***
     * 提取封面中的图片
     */
    public void fetchImages(WmNewsDtoSave dtoSave){
        if(dtoSave.getType().intValue()==-1){
            //自动，需要从content中提取图片
            List<String> images = new ArrayList<String>();
            for (ContentNode contentNode : dtoSave.getContent()) {
                String type = contentNode.getType();
                if(type.equals("image")){
                    String value = contentNode.getValue();
                    images.add(value);
                    if(images.size()>=3){
                        break;
                    }
                }
            }
            //设置图片
            dtoSave.setImages(images);
        }
    }

    public static void main(String[] args) {
       /* List<String> lists = new ArrayList<String>();
        lists.add("AAAA");
        lists.add("BBB");
        lists.add("[C]CCC");
        System.out.println(lists.toString().substring(1,lists.toString().length()-1).replace(" ",""));*/

       /* System.out.println(LocalDateTime.now());
        System.out.println(LocalDate.now());
        System.out.println(LocalTime.now());
        System.out.println(new Date());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        System.out.println(simpleDateFormat.format(new Date()));

        LocalDateTime now = LocalDateTime.now();
        System.out.println(now.getSecond());*/

    }


}
